package com.rxnetwork.sample.utils.interceptor

import android.util.Log
import com.rxnetwork.sample.utils.network.JsonFormatUtil
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * 接口请求日志拦截打印
 */
class AppLogInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val mediaType = response.body().contentType()
        val content = response.body().string()
        Log.i(TAG, HEADER_TITLE + response.headers().toString())
        Log.i(TAG, REQUEST_TITLE + response.request().toString())
        Log.i(TAG, RESPONSE_TITLE + response.toString())
        //格式化输出
        Log.i(TAG, CONTENT_TITLE + JsonFormatUtil.format(content))
        if (response.body() != null) {
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build()
        } else {
            return response
        }
    }

    companion object {

        private val TAG = "RxNetWorkApiLog"
        private val CONTENT_TITLE = "Api Content-->:"
        private val HEADER_TITLE = "Api Header-->:"
        private val REQUEST_TITLE = "Api Request-->:"
        private val RESPONSE_TITLE = "Api Response-->:"
    }
}
